<template>
  <div>
    <div class="button_flex">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5" v-if="props.tabsType == 'enterprise'">
          <el-cascader v-model="zskData" :options="options" @change="getList" />
        </el-col>
        <el-col :span="1.5">
          <el-button class="filter-item" :icon="Refresh" plain :disabled="selectionArray.length == 0"
            @click="restoreBtnClick">还原</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" class="filter-item" plain :icon="DeleteFilled"
            @click="deleteBtnClick()">清空回收站</el-button>
        </el-col>
      </el-row>

    </div>
    <div class="table_boxClass">
      <el-table ref="multipleTable" v-loading="recycleLoading" :data="tableData" tooltip-effect="dark"
        style="width: 100%" height="610px" :highlight-current-row="true" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="文件名" show-overflow-tooltip>
          <template v-slot="scope">
            <svg-icon :icon-class="selectSvgIcons(scope.row)"
              style="font-size: 30px; vertical-align: middle; margin-right: 6px"></svg-icon>
            <span class="realName_class">{{ scope.row.realName
              }}{{ scope.row.suffix ? "." + scope.row.suffix : "" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="原始路径">
          <template v-slot="scope">
            {{ scope.row.superiorsPath.replace(/\//g, "\\") }}
          </template>
        </el-table-column>
        <el-table-column label="删除时间">
          <template v-slot="scope">
            {{ scope.row.deleteTime }}
          </template>
        </el-table-column>
        <el-table-column label="大小">
          <template v-slot="scope">
            {{ filterSizeUnit(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="删除人">
          <template v-slot="scope">
            {{ scope.row.deleteBy }}
          </template>
        </el-table-column>
        <el-table-column label="创建人">
          <template v-slot="scope">
            {{ scope.row.createBy }}
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="changePage(tabsType)" />
    </div>

    <!-- 还原选择位置 -->
    <div>
      <el-dialog v-model="dialogRestore" title="请选择还原位置" width="500" :before-close="cloeRestoreDialog">
        <div class="treeElClass">
          <el-tree style="max-width: 600px" :data="treeRestoreList" :props="defaultProps" node-key="id" lazy
            :load="loadNode" :highlight-current="true" :default-expanded-keys="expandedKeys"
            :expand-on-click-node="false" @node-click="handleNodeClick">
            <template #default="{ node, data }">
              <svg-icon :icon-class="node.expanded ? 'file-open' : 'file-close'"></svg-icon>
              <span>{{ node.label }}</span>
            </template>
          </el-tree>
        </div>
        <div class="path">
          还原路径： {{ treeRestorePathObj.path.replace(/\//g, "\\") }}
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogRestore = false">取消</el-button>
            <el-button type="primary" @click="SureDialogRestoreClick">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">

// import recycleBinApi from "@/api/documents/recycleBinApi";
import { apiPersonalTreeFileSelectPersonalTree, apiRecycleBinFoxBaseDeleteAll } from "@/api/documents/personalApi.js"
// import teamFilelApi from "@/api/documents/teamFileApi.js";
// import enterpriseApi from "@/api/documents/enterpriseApi.js";
import { Refresh, DeleteFilled } from '@element-plus/icons-vue'
import { getRecycleBinFoxBaseSelect, apiTreeFileSelectTree, deleteAllRecycleFile, restoreRecycleFile, apienterpriseFilesTreeQuery, apirecoverFilepath } from '@/api/fileManage/secondaryRecycle'
import { apiEnterpriseKnowledgeList } from '@/api/enterprise/enterpriseConfig/index'
import { apiFilesTreeQuery } from '@/api/fileManage/secondaryRecycle/index'


const { proxy } = getCurrentInstance() as any
const total = ref(0)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,

})
const recycleLoading = ref(false)
const dialogRestore = ref(false)
const tableData = ref([])
const treeRestoreList = ref([])
const selectionArray = ref([])
const defaultProps = ref({
  children: 'children',
  label: 'realName',
  isLeaf: 'leaf'
})
const expandedKeys = ref([0])
const treeRestorePathObj = reactive({
  path: "",
  id: null,
  userName: "",
  parentId: null,
})

const zskData = ref()
const options = ref<any[]>([])
const handleNodeClick = (data) => {
  treeRestorePathObj.path = data.path
  treeRestorePathObj.parentId = data.id
}

const props = defineProps({
  rowData: {
    type: Object,
    require: true,
    default: () => ({})
  },
  tabsType: {
    type: String,
    require: true,
    default: "personal",
  },

})


// 使用 watch 监听 rowData
watch(
  () => ({
    rowData: props.rowData,
    tabsType: props.tabsType
  }),
  (newVal) => {
    zskData.value = []
    tableData.value = []
    treeRestoreList.value = []
    // Logic to handle changes to both rowData and tabsType
    if (newVal.rowData && newVal.rowData.userId) {
      treeRestorePathObj.userName = newVal.rowData.userName
      treeRestorePathObj.id = newVal.rowData.userId
      getFileList(newVal.rowData.userId)

    }
    if (newVal.tabsType == "enterprise") {
      getInit()
    } if (newVal.tabsType == "team") {
      treeRestorePathObj.id = newVal.rowData.id
      getTeamInit(newVal.rowData.id)
      // getFileList(newVal.rowData.userId)
    }
  },
  { immediate: true }
)

// 个人文档文件列表
const getFileList = async (id) => {
  if (!id) {
    console.warn('rowData.id is not available')
    return
  }
  try {
    const res = await getRecycleBinFoxBaseSelect({
      id: id, // 直接使用传入的 id
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      fileTreeType: props.tabsType,
    })
    if (res.code == 200) {
      tableData.value = res.data.rows
      total.value = res.data.total
      recycleLoading.value = false
    }
  } catch (error) {
    console.error('Error fetching file list:', error)
  }
}

// 企业文档文件列表
const getEnterpriseList = async () => {
  tableData.value = []
  recycleLoading.value = true
  try {
    const res = await getRecycleBinFoxBaseSelect({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      fileTreeType: props.tabsType,
      id: zskData.value[1],
    })
    if (res.code == 200) {
      tableData.value = res.data.rows
      total.value = res.data.total
      recycleLoading.value = false
    }
  } catch (error) {
    recycleLoading.value = false
  }
}


const getInit = async () => {
  let res: any = await apiEnterpriseKnowledgeList()
  if (res.code == 200) {
    options.value = res.data.map((item: any, index: number) => {
      return {
        value: index,
        label: item.classifyName,
        children: item.tree.map(item1 => {
          return {
            value: item1.id,
            label: item1.realName,
          }
        })
      }
    })
  }
}

const getList = () => {
  getEnterpriseList()
}
// 团队文件
const getTeamInit = async (id) => {
  const res = await getRecycleBinFoxBaseSelect({
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    fileTreeType: props.tabsType,
    id: id,
  })
  if (res.code == 200) {
    tableData.value = res.data.rows
    total.value = res.data.total
    recycleLoading.value = false
  }
}


// 翻页
const changePage = (val: any) => {
  if (val == 'enterprise') {
    getEnterpriseList()
  }
  if (val == 'personal') {
    getFileList(props.rowData.userId)
  }
  if (val == 'team') {
    getTeamInit(props.rowData.id)
  }
}

// 文件图标
const selectSvgIcons = (item: any) => {
  var iconArray = [
    {
      suffix: ["xls", "xlsx", "xlsb", "xlsm"],
      icon: "Excel"
    },
    {
      suffix: ["doc", "docx"],
      icon: "Word"
    },
    {
      suffix: ["ppt", "pptx", "pps", "ppsx"],
      icon: "PPT"
    },
    {
      suffix: ["mp3", "wav", "wmv"],
      icon: "music"
    },
    {
      suffix: ["mp4", "m2v", "mkv"],
      icon: "shipin"
    },
    {
      suffix: ["png", "jpg", "jpeg", "bmp", "ico"],
      icon: "tupian"
    },
    {
      suffix: ["gif"],
      icon: "Gif"
    },
    {
      suffix: ["pdf"],
      icon: "Pdf"
    },
    {
      suffix: ["txt"],
      icon: "txt"
    },
    {
      suffix: ["sql"],
      icon: "shujuku"
    },
    {
      suffix: ["rar", "zip", "rar4", "7z"],
      icon: "yasuobao"
    },
    {
      suffix: ["html"],
      icon: "chengxu"
    },
    // 自定义表单文档
    {
      suffix: ["richText"],
      icon: "biaodan3"
    }
  ]
  if (item.type == "folder") {
    return "file-close"
  } else {
    let result: boolean
    for (let i = 0; i < iconArray.length; i++) {
      const iconArrayItem = iconArray[i]
      const suffixItem = iconArrayItem.suffix
      const icon = iconArrayItem.icon
      result = suffixItem.some(function (val) {
        return val == item.suffix
      })
      if (result) {
        return icon
      }
    }
    return "weizhiwenjian"
  }
}
// 还原
const restoreBtnClick = async () => {
  dialogRestore.value = true
  console.log(props.tabsType, 'props.rowData')
  if (props.tabsType == 'enterprise') {
    let res: any = await apienterpriseFilesTreeQuery({ id: zskData.value[1] })
    if (res.code == 200) {
      treeRestorePathObj.path = res.data.path
      treeRestorePathObj.parentId = res.data.id
      treeRestoreList.value = res.data.children.filter(item => item.type == "folder")
    }
  }
  if (props.tabsType == 'personal') {
    let res: any = await apiPersonalTreeFileSelectPersonalTree({
      type: 11,
      sortDesc: "type,create_time",
      username: props.rowData.userName,
    })
    if (res.code == 200) {
      treeRestorePathObj.path = res.data.path
      treeRestorePathObj.parentId = res.data.id
      treeRestoreList.value = res.data.children.filter(item => item.type == "folder")
    }
  }
  if (props.tabsType == 'team') {
    console.log(props.rowData, 'props.rowData')
    let res: any = await apiFilesTreeQuery({
      id: props.rowData.headNodeId,
    })
    if (res.code == 200) {
      treeRestorePathObj.path = res.data.path
      treeRestorePathObj.parentId = res.data.id
      treeRestoreList.value = res.data.children.filter(item => item.type == "folder")
    }
  }
}

// loadTree
const loadNode = async (node: any, resolve: any) => {
  if (node.level == 0) {
    return resolve(node.data)
  }
  if (props.tabsType == 'enterprise') {
    let res: any = await apienterpriseFilesTreeQuery({ id: node.data.id })
    let childrenArr = res.data.children.filter(item => item.type == "folder")
    return resolve(childrenArr)
  }
  if (props.tabsType == 'personal') {
    let res: any = await apiPersonalTreeFileSelectPersonalTree({
      parentId: node.data.id,
    })
    if (res.code == 200) {
      let childrenArr = res.data.children.filter(item => item.type == "folder")
      return resolve(childrenArr)
    }
  }
  if (props.tabsType == 'team') {
    let res: any = await apiFilesTreeQuery({
      id: node.data.id,
    })
    if (res.code == 200) {
      let childrenArr = res.data.children.filter(item => item.type == "folder")
      return resolve(childrenArr)
    }
  }
}

// 清空回收站
const deleteBtnClick = async () => {
  if (tableData.value.length == 0) {
    ElMessage.warning("暂无可清空的文件")
    return
  }
  if (props.tabsType == 'enterprise') {
    const res = await deleteAllRecycleFile({
      type: props.tabsType,
      id: zskData.value[1],
    })
    if (res.code == 200) {
      ElMessage.success("清空成功")
      getEnterpriseList()
    }
  } else {
    const res = await apiRecycleBinFoxBaseDeleteAll({
      type: props.tabsType,
    })
    if (res.code == 200) {
      ElMessage.success("清空成功")
      if (props.tabsType == 'personal') {
        getFileList(props.rowData.userId)
      } else {
        getTeamInit(props.rowData.id)
      }
    }
  }
}




// 表格选中
const handleSelectionChange = (val: any) => {
  selectionArray.value = val
}


// 点击树节点
const treeRestoreNodeClick = (data: any) => {

}
// 还原位置弹窗确定
const SureDialogRestoreClick = () => {
  let idsData = selectionArray.value.map((item) => {
    return item.id
  })
  console.log(idsData, 'idsData')
  apirecoverFilepath({
    ids: idsData,
    id: treeRestorePathObj.id,
    type: props.tabsType,
    parentId: treeRestorePathObj.parentId,
  }).then((res: any) => {
    ElMessage.success("已还原到原文件目录")
    cloeRestoreDialog()
    getEnterpriseList()
  })
}

// 还原位置弹窗关闭
const cloeRestoreDialog = () => {
  dialogRestore.value = false
  treeRestorePathObj.path = ''
  treeRestorePathObj.parentId = null
}

const filterSizeUnit = (val) => {
  //  if(!val) return "-"
  // if(val===0) return "0 B"
  // let k = 1024
  // let sizes = ['B','KB','MB','GB','TB','PB','EB','ZB','YB']
  // let i = Math.floor(Math.log(val) /Math.log(k))
  // return (val / Math.pow(k,i)).toPrecision(3) + " " + sizes[i]
  if (isNaN(val)) return '-'
  if (val < 0) return '-'
  var list = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  var temp = Math.floor(Math.log(val) / Math.log(2))
  if (temp < 1) temp = 0
  var num = Math.floor(temp / 10)
  val = val / Math.pow(2, 10 * num)
  // if (val.toString().length > val.toFixed(2).toString().length) val = val.toFixed(2);
  if (val.toString().length > val.toFixed(2).toString().length) val = Math.floor(val * 100) / 100
  return val + ' ' + list[num]
}
</script>

<style lang="scss" scoped>
.button_flex {
  margin-top: 20px;
  margin-bottom: 20px;


}

.table_boxClass {
  max-height: 74vh;
  overflow-y: auto;
}

.realName_class {
  line-height: 40px;
}

.treeElClass {
  max-height: 30vh;
  overflow-y: auto;
}

.path {
  font-size: 14px;
  color: #606266;
  padding: 20px 0 0;
}
</style>
